package com.liuwei.netty.reconnect;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyClient {
    private Bootstrap bootstrap;

    public Bootstrap getBootstrap() {
        return bootstrap;
    }

    public void setBootstrap(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        NettyClient nettyClient = new NettyClient();
        nettyClient.setBootstrap(bootstrap);
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new NettyReconnectClientHandler(nettyClient));
                    }
                });
        nettyClient.connect();
    }

    public void connect(){
        // 连接服务器
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9090);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                boolean result = future.isSuccess();
                if(!result) {
                    // 连接失败,重新连接
                    future.channel().eventLoop().schedule(()-> {
                        log.info("尝试与服务器重新连接中");
                        connect();
                    }, 2000, TimeUnit.MILLISECONDS);
                } else {
                    log.info("与服务器连接成功");
                }
            }
        });
    }
}
